package com.adnaan.backend.controller;

import com.adnaan.backend.common.config.FileUpload;
import com.adnaan.backend.common.utils.PageResult;
import com.adnaan.backend.common.utils.PageUtils;
import com.adnaan.backend.common.utils.R;
import com.adnaan.backend.entity.SysUser;
import com.adnaan.backend.service.SysUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * author: adnaan
 * create: 2024-06-11 20:04
 * Description:
 */
@Tag(name = "用户接口", description = "用户相关功能")
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private FileUpload fileUpload;

    @Operation(summary = "用户列表")
    @GetMapping("/list")
    public R list(@RequestParam Integer pageNum,
                  @RequestParam Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<SysUser> list = sysUserService.list();
        PageInfo<SysUser> pageInfo = new PageInfo<>(list);
        PageResult pageResult = PageUtils.getPageResult(pageInfo);
        return R.success(pageResult);
    }

    @Operation(summary = "删除用户")
    @DeleteMapping("/delete")
    public R delete(@RequestParam Long id) {
        if(id == 1L) {
            return R.error("超级管理员不能删除");
        }
        boolean b = sysUserService.removeById(id);
        return R.toAjax(b ? 1 : 0);
    }

    @Operation(summary = "修改用户")
    @PutMapping("/update")
    public R update(@RequestBody SysUser sysUser) {
        boolean b = sysUserService.updateById(sysUser);
        return R.toAjax(b ? 1 : 0);
    }

    @Operation(summary = "上传头像")
    @PostMapping("/upload")
    public R uploadBanner(@RequestParam MultipartFile file) {
        String url = fileUpload.upload(file, "avatar");
        return R.success().put("url", url);
    }

}
